import re
from typing import List, Dict, Any
import os
import chardet


def _detect_encoding(file_path: str) -> str:
    """检测文件编码"""
    with open(file_path, 'rb') as f:
        raw_data = f.read()
        result = chardet.detect(raw_data)
        return result['encoding'] or 'utf-8'


class FunctionParser:
    def __init__(self):
        self.function_pattern = re.compile(
            r'(?P<return_type>[\w\s*]+)\s+'  # 返回类型
            r'(?P<function_name>[\w:]+)\s*'  # 函数名
            r'\((?P<parameters>[^)]*)\)\s*'  # 参数
            r'(?P<body>{[^}]*})'  # 函数体
        )

    def parse_file(self, file_path: str) -> List[Dict[str, Any]]:
        """解析文件中的所有函数"""
        try:
            # 检测文件编码
            encoding = _detect_encoding(file_path)
            
            # 使用检测到的编码读取文件
            with open(file_path, 'r', encoding=encoding, errors='replace') as f:
                content = f.read()
            
            functions = []
            for match in self.function_pattern.finditer(content):
                function = {
                    'name': match.group('function_name'),
                    'return_type': match.group('return_type').strip(),
                    'parameters': match.group('parameters').strip(),
                    'body': match.group('body'),
                    'start_line': content[:match.start()].count('\n') + 1,
                    'end_line': content[:match.end()].count('\n') + 1,
                    'file_path': file_path
                }
                functions.append(function)
            
            return functions
        except Exception as e:
            print(f"解析文件 {file_path} 时出错: {str(e)}")
            return []

    def get_function_context(self, function: Dict[str, Any], content: str) -> str:
        """获取函数的上下文信息"""
        # 获取函数前的注释
        lines = content.split('\n')
        start_line = function['start_line']
        context_lines = []
        
        # 向上查找注释
        i = start_line - 2
        while i >= 0 and (lines[i].strip().startswith('//') or lines[i].strip().startswith('/*')):
            context_lines.insert(0, lines[i])
            i -= 1
        
        # 获取函数声明和实现
        context_lines.extend(lines[function['start_line']-1:function['end_line']])
        
        return '\n'.join(context_lines) 